package org.hackystat.ui.chart.jfc.fileresource;

import java.io.File;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.FileRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.Variant;

/**
 * The ChartServer serves rendered charts for the public.
 *
 * @author Pavel Senin.
 *
 */
public class ChartFileResource
    extends Resource {

  /** To be retrieved from the URL. */
  private String chartName;

  /**
   * Provides the following representational variants: TEXT_XML.
   *
   * @param context The context.
   * @param request The request object.
   * @param response The response object.
   */
  public ChartFileResource(Context context, Request request, Response response) {
    super(context, request, response);
    this.chartName = (String) request.getAttributes().get("chartname");
    System.out.println(request.toString());
    getVariants().clear(); // copied from BookmarksResource.java, not sure why needed.
    getVariants().add(new Variant(MediaType.IMAGE_ALL));
  }

  /**
   * Returns the representation of the User resource.
   *
   * @param variant The representational variant requested.
   * @return The representation.
   */
  @Override
  public Representation getRepresentation(Variant variant) {
    Representation result = null;
    ChartFileManager manager = (ChartFileManager) getContext().getAttributes().get(
        "ChartFileManager");
    if (manager == null) {
      throw new RuntimeException("Failed to find FileManager");
    }
    if (variant.getMediaType().equals(MediaType.IMAGE_ALL)) {
      File chartImage = manager.getChartImage(this.chartName);
      result = new FileRepresentation(chartImage, MediaType.IMAGE_ALL, 300);
    }
    return result;
  }

  /**
   * Indicate the DELETE method is supported.
   *
   * @return True.
   */
  @Override
  public boolean allowDelete() {
    return false;
  }

  /**
   * Indicate the POST method is supported.
   *
   * @return True.
   */
  @Override
  public boolean allowPost() {
    return false;
  }

}
